package com.swpu.service.impl;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.core.util.IdUtil;
import com.swpu.common.CacheConstants;
import com.swpu.component.RedisUtils;
import com.swpu.exception.BusinessException;
import com.swpu.model.dto.CaptchaResult;
import com.swpu.model.entity.SysUser;
import com.swpu.mapper.SysUserMapper;
import com.swpu.model.query.UserRegisterQuery;
import com.swpu.service.SysUserService;
import com.swpu.utils.MD5Util;
import com.swpu.utils.RSAUtil;
import com.swpu.utils.TokenUtil;
import com.swpu.utils.UuidUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser selectById(String userId) {
        return sysUserMapper.selectById(userId);
    }


    /**
     * 获取验证码
     *
     * @return 验证码
     */
    @Override
    public CaptchaResult getCaptcha() {
        int width = 120;
        int height = 40;
        int interfereCount = 2;
        int codeLength = 4;
        AbstractCaptcha captcha = CaptchaUtil.createShearCaptcha(width, height, codeLength, interfereCount);
        String captchaCode = captcha.getCode();
        String imageBase64Data = captcha.getImageBase64Data();
        // 验证码文本缓存至Redis，用于登录校验
        String captchaKey = IdUtil.fastSimpleUUID();
        redisUtils.setex(CacheConstants.CAPTCHA_CODE_PREFIX + captchaKey,captchaCode,
                120);
        return CaptchaResult.builder()
                .captchaKey(captchaKey)
                .captchaBase64(imageBase64Data)
                .build();
    }

    @Override
    public String login(String username, String password) {
        SysUser sysUser = sysUserMapper.selectByUsername(username);
        if (sysUser == null) {
            throw new BusinessException("用户名或密码不正确");
        }
        String decryptPassword;
        try {
            decryptPassword = RSAUtil.decrypt(password);
        } catch (Exception e) {
            throw new BusinessException("密码解密失败");
        }
        String salt = sysUser.getSalt();
        String md5Password = MD5Util.sign(decryptPassword, salt, "UTF-8");
        if (!md5Password.equals(sysUser.getPassword())) {
            throw new BusinessException("用户名或密码不正确");
        }
        String token;
        try {
            token = TokenUtil.generateToken(sysUser.getId());
        } catch (Exception e) {
            throw new BusinessException("生成token异常，请联系管理员！");
        }

        return token;
    }

    @Override
    public String refreshToken(String userId) {
        try {
            return TokenUtil.generateRefreshToken(userId);
        } catch (Exception e) {
            throw new BusinessException("生成token异常，请联系管理员！");
        }
    }
    @Override
    public void register(UserRegisterQuery userRegisterQuery) {
        String username = userRegisterQuery.getUsername();
        SysUser userByLoginName = sysUserMapper.selectByUsername(username);
        if (userByLoginName != null) {
            throw new BusinessException("用户名已存在");
        }
        String decryptPassword;
        try {
            decryptPassword = RSAUtil.decrypt(userRegisterQuery.getPassword());
        } catch (Exception e) {
            throw new BusinessException("密码解密失败！");
        }
        String id = UuidUtil.getShortUuid();
        String salt = UuidUtil.getUuid();
        String md5Password = MD5Util.sign(decryptPassword, salt, "UTF-8");
        SysUser user = new SysUser();
        user.setId(id);
        user.setPassword(md5Password);
        user.setUsername(username);
        user.setSalt(salt);
        sysUserMapper.insertSysUser(user);
    }

}
